package cn.laowen.basic.interceptors;

import cn.laowen.basic.anno.PreAuthorize;
import cn.laowen.basic.jwt.JwtUtils;
import cn.laowen.basic.jwt.LoginResult;
import cn.laowen.basic.jwt.Payload;
import cn.laowen.basic.jwt.RsaUtils;
import cn.laowen.system.domain.Permission;
import cn.laowen.system.mapper.PermissionMapper;
import cn.laowen.user.domain.Logininfo;
import cn.laowen.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 拦截器
 */
@Component//非受容器管理的对象注入加此注解
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 后台登录拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取 U-TOKEN
        String token = request.getHeader("U-TOKEN");//jwt串
        //因为都需要设置编码器,所以抽到上面公用
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");//设置编码集
        if(StringUtils.hasLength(token)){
           /* //2.根据U-TOKEN从redis中获取登录信息
            Object loginTmp = redisTemplate.opsForValue().get(token);*/
            //获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            //使用公钥 解密jwt
            Payload<LoginResult> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginResult.class);
            LoginResult loginResult = payload.getUserInfo();
            if (loginResult != null){
                    //增加权限校验-------
                    //1.如果是员工需要校验权限
                    Logininfo logininfo = loginResult.getLogininfo();//把object强转为Logininfo
                    if (logininfo.getType() == 0){//type=0,代表员工，需要校验权限
                        //1.1得到当前请求的资源url
                        HandlerMethod method = (HandlerMethod) handler;
                        PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);//打上此注解的接口,就需要校验权限
                        if(annotation != null){
                            //拿到本次请求的sn
                            String currentSn = annotation.value();
                            //查询出当前登录人所拥有的按钮资源 permissions
                            //List<String> permissions = permissionMapper.loadPermissionByLogininfoId(logininfo.getId());
                            //1.3判断permissionns是否包含url
                            if(!loginResult.getPermissions().contains(currentSn)){//如果permissions不包含本次请求的sn
                                //1.3.2不包含---提示权限不足，请联系管理员
                                PrintWriter writer = response.getWriter();
                                writer.write("{\"success\":false,\"message\":\"noPermission\"}");//提示语：noPermission
                                writer.flush();//刷出
                                writer.close();//关流
                                return false;//阻止放行
                            }
                            //1.3.1包含---说明有权限访问,放行
                        }
                    }
                //只要前端还在操作,就刷新过期时间
               /* redisTemplate.opsForValue().set(
                        token,
                        loginTmp,
                        30,
                        TimeUnit.MINUTES
                );*/
                return true;//登陆了,放行
            }
        }
        //3.跳到登录

        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");//写出
        writer.flush();//刷出
        writer.close();//关流
        return false;//阻止放行

    }

}